﻿using FDStudio.Core.Container;
using FDStudio.Core.Entities;
using FDStudio.Core.Entities.Query;
using FDStudio.Core.Runtime;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;

namespace FDStudio.Core.Repositories
{
    /*
     CreatedOn: 2018-01-26
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 只读仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class ReadOnlyRepository<T> : IReadOnlyRepository<T> where T : class, IEntity
    {
        private IContainer _container;

        public ReadOnlyRepository()
        {
            _container = RuntimeContext.Current.Container;
        }

        public IRepositoryContext Context => _container.Resove<IReadOnlyRepositoryContext>();

        public virtual C RepositoryContext<C>() where C : IRepositoryContext
        {
            return (C)Context;
        }

        public int Count(Expression<Func<T, bool>> condition)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().Count(condition);
        }

        public void ExecuteDataReader(string sql, object parameter, Action<IDataReader> read, CommandType commandType = CommandType.Text)
        {
            RepositoryContext<IReadOnlyRepositoryContext>().ExecuteDataReader(sql, read, parameter, commandType);
        }

        public U ExecuteScalar<U>(string sql, object parameter)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().ExecuteScalar<U>(sql, parameter);
        }

        public bool Exists(Expression<Func<T, bool>> condition)
        {
            return Count(condition) > 0;
        }

        public T Get(long id)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().Get<T>(id);
        }

        public T Get(Expression<Func<T, bool>> condition)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().Get<T>(condition);
        }

        public IEnumerable<T> GetList(Expression<Func<T, bool>> condition)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().GetList(condition, null);
        }

        public IEnumerable<T> GetList(Expression<Func<T, bool>> condition, IQueryOrder<T> orderBy)
        {
            return RepositoryContext<IReadOnlyRepositoryContext>().GetList(condition, orderBy);
        }
    }
}
